package com.ghh.controller.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ghh.pojo.Permission;
import com.ghh.pojo.Role;
import com.ghh.pojo.User;
import com.ghh.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class SecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取用户
        User user = userService.findByUsername(username);
        if (user == null){
            //用户名不存在，认证失败
            return null;
        }
        Set<GrantedAuthority> set = new HashSet<>();

        //动态授权
        //获取当前用户的角色集合的地址
        Set<Role> roles = user.getRoles();
        //遍历集合
        for (Role role : roles) {
            //为用户的角色赋值
            set.add(new SimpleGrantedAuthority(role.getKeyword()));
            //获取当前角色的权限集合
            Set<Permission> permissions = role.getPermissions();
            //遍历权限集合
            for (Permission permission : permissions) {
                //动态为角色授权
                set.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //返回查询到的用户名，密码，角色集合
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),set);
    }
}
